// Parser for day-of-week (DOW) specifications

module.exports = (function() {
  "use strict";

  function DOWParser(dowRE, dowREc1,
                     rangeDelimRE, listDelimRE,
                     convert2num) {
    function getREsrc(re) {
      if (re instanceof RegExp)
        return re.source;
      return re.toString();
    }

    this.dowREsrc = getREsrc(dowRE);
    this.dowREc1src = getREsrc(dowREc1);
    this.rangeDelimREsrc = getREsrc(rangeDelimRE);
    this.listDelimREsrc = getREsrc(listDelimRE);
    this.convert2num = convert2num instanceof Function?
      convert2num : function(text) {
        return convert2num[text];
      };

    this.rangeREsrc = "(?:" + this.dowREsrc + ")(?:(?:" +
      this.rangeDelimREsrc + ")(?:" + this.dowREsrc + "))?";
    this.rangeREc2src = "(?:" + this.dowREc1src + ")(?:(?:" +
      this.rangeDelimREsrc + ")(?:" + this.dowREc1src + "))?";
    this.listREsrc = "(?:" + this.rangeREsrc + ")(?:(?:" +
      this.listDelimREsrc + ")(?:" + this.rangeREsrc + "|.*?))*";

    this.listDelimRE = new RegExp(this.listDelimREsrc, "i");
    this.rangeREc2 = new RegExp(this.rangeREc2src, "i");
  }

  var rangeDelimREsrc = /\s*(?:to|[-\u2013])\s*/.source;

  var dowParserEN = new DOWParser(/Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Weekday|Weekend|(?:(?:Sun|Mon|Tue|Wed|Thur?|Fri|Sat)\.?)/,
                                  /(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Weekday|Weekend|Sun|Mon|Tue|Wed|Thur?|Fri|Sat)\.?/,
                                  rangeDelimREsrc,
                                  /\s*(?:\band\b|&)\s*/, {
    Sunday: 0,
    Monday: 1,
    Tuesday: 2,
    Wednesday: 3,
    Thursday: 4,
    Friday: 5,
    Saturday: 6,

    Sun: 0,
    Mon: 1,
    Tue: 2,
    Wed: 3,
    Thu: 4,
    Thur: 4,
    Fri: 5,
    Sat: 6,

    Weekday: [1, 5],
    Weekend: [6, 0],
  });

  var dowParserZH = new DOWParser(/(?:星期)?[日一二三四五六]/,
                                  /(?:星期)?([日一二三四五六])/,
                                  /\s*[-至–]\s*/,
                                  /\s*[、及&]\s*/, {
    日: 0,
    一: 1,
    二: 2,
    三: 3,
    四: 4,
    五: 5,
    六: 6,
  });
  //overrides:
  dowParserZH.listREsrc = "星期" + dowParserZH.listREsrc;
  dowParserZH.listRE = new RegExp(dowParserZH.listREsrc);


  function chooseInstance(text) {
    if (text.match(dowParserZH.listRE))
      return dowParserZH;
    return dowParserEN;
  }


  return {
    listREsrc: "(?:" + dowParserEN.listREsrc +
      ")|(?:" + dowParserZH.listREsrc +
      ")",

    chooseInstance: chooseInstance,
  };
}());

